package com.wk.worksetter.viewmodels

import android.content.pm.PackageInfo
import android.graphics.drawable.Drawable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wk.worksetter.db.WorkDatabase
import com.wk.worksetter.db.WorkEntity
import com.wk.worksetter.utils.WorkUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author peng
 * @date 2021/1/29
 * 说明
 */
class MainViewModel : ViewModel() {

    private val _notRunningInfos: MutableLiveData<List<WorkEntity>> = MutableLiveData()
    val notRunningInfos: LiveData<List<WorkEntity>> = _notRunningInfos

    private val _packageInfos: MutableLiveData<List<PackageInfo>> = MutableLiveData()
    val packageInfos: LiveData<List<PackageInfo>> = _packageInfos

    val appIconWithPackage : MutableMap<String,Drawable?> = HashMap<String,Drawable?>()

    private val dao = WorkDatabase.instance.articleDao


    init {
        viewModelScope.launch(Dispatchers.IO){
            val packageInfos = WorkUtil.getAllInstalledApps()
            getAllIcons(packageInfos)
            _packageInfos.postValue(packageInfos)
        }
    }

    private fun getAllIcons(packageInfos: List<PackageInfo>) {
        packageInfos.forEach {
            val drawable = WorkUtil.getAppIcon(it)
            appIconWithPackage.put(it.packageName,drawable)
        }
    }

    fun loadNotRunningInfos() {
        viewModelScope.launch(Dispatchers.IO) {
            val infos = dao.getAllWorks(false)
            _notRunningInfos.postValue(infos)
        }
    }

    fun addPackInfoToList(info: PackageInfo) {
        val entity = WorkEntity(
            packageName = info.packageName,
            packageLabel = WorkUtil.getAppLabelName(info)
        )
        viewModelScope.launch(Dispatchers.IO){
            dao.insertWork(listOf(entity))
            loadNotRunningInfos()
        }
    }

}